package com.atguigu.gulimail.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimail.auth.feign.MemberFeignService;
import com.atguigu.gulimail.auth.vo.UserVo;
import com.atguigu.gulimail.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class OAuth2Controller {


    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        long start = System.currentTimeMillis();
        //通过code获取 tocken
        //https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
           Map<String,String> map=new HashMap<>();
           map.put("code", code);
           map.put("client_id","33d15ea55cc12cd3cb33e00387dfe9b391d723e4a2b54b8b83e2ce8572de12e7");
           map.put("redirect_uri","http://auth.gulimail.com/oauth2.0/gitee/success");
           map.put("client_secret","5986b1cee2c597ece1a6524d92915449bf5f042c48d914a1e3cbe9c4e5814540");


        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token?grant_type=authorization_code", "post", new HashMap<>(), null, map);

        //处理
        if (response.getStatusLine().getStatusCode()==200){
            //如果获取的状态码是200
            HttpEntity entity = response.getEntity();
            //EntityUtils 是专门用来处理HttpEntity
            String s = EntityUtils.toString(entity);
            SocialUser socialUser = JSON.parseObject(s, SocialUser.class);

            /**
             * {
             *     "access_token": "5f554d2af0140d6b82855b9c27732389",
             *     "token_type": "bearer",
             *     "expires_in": 86400,
             *     "refresh_token": "a40c6512ac2e2ad37089c9aec404fe3e543a0a40d25425213d7eadffff99f3d2",
             *     "scope": "user_info",
             *     "created_at": 1643012859
             * }
             */
            //如果当前用户是第一次登录，那么就自动注册进来。

            Map<String,String>map1=new HashMap<>();
            map1.put("access_token", socialUser.getAccess_token());
            HttpResponse re = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), map1);
            if (re.getStatusLine().getStatusCode()==200){
                UserVo giteeVo=new UserVo();
                String s1 = EntityUtils.toString(re.getEntity());
                JSONObject jsonObject = JSON.parseObject(s1);
                String id =  jsonObject.get("id").toString();
                String name = (String) jsonObject.get("name");
                giteeVo.setId(id);
                giteeVo.setName(name);

            //调用远程方法。
                R authlogin = memberFeignService.authlogin(giteeVo);
                if (authlogin.getCode()==0){

                    MemberResponseVo data = authlogin.getData(new TypeReference<MemberResponseVo>() {
                    });
                    long end = System.currentTimeMillis();
                    log.info("获取到的:data{}",data);
                    log.info("耗时：{}",(end-start));
                    session.setAttribute(AuthServerConstant.LOGIN_USER, data);

                    return "redirect:http://gulimail.com";
                }else{
                    return "redirect:http://auth.gulimail.com/login.html";
                }
            }
        }else{
            //否则 换回登陆页面。
            return "redirect:http://auth.gulimail.com/login.html";
        }
        return "redirect:http://gulimail.com";
    }

}
